package com.mf.elephant.service.basic.impl;

import com.mf.elephant.common.utils.Dom4jUtils;
import com.mf.elephant.domain.basic.template.Template;
import com.mf.elephant.service.basic.TemplateService;
import org.dom4j.Document;
import org.dom4j.Node;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板管理Service实现类
 * User: zhaoming
 * Date: 2016-07-02
 * To change this template use File | Settings | File Templates.
 **/
@Service
public class TemplateServiceImpl implements TemplateService {

    /**
     * 查询全部模板列表
     * @return 数据类型映射列表
     */
    public List<Template> selectAll(){
        List<Template> templates = new ArrayList<>();
        String fileName = this.getClass().getResource("/").toString();
        fileName = fileName.substring("file:/".length(), fileName.length())+ File.separator + "data" + File.separator + "xml" + File.separator + "template.xml";
        Dom4jUtils dom4jUtil = new Dom4jUtils();
        Document document =  dom4jUtil.read(fileName);
        List<Node> list = dom4jUtil.selectNodes(document,"//template");
        for(Node node : list){
            Template t = new Template();
            t.setCode(node.valueOf("@code"));
            t.setName(node.valueOf("@name"));
            t.setTemplateName(node.valueOf("@templateName"));
            t.setFilePath(node.valueOf("@filePath"));
            t.setFileName(node.valueOf("@fileName"));
            templates.add(t);
        }
        return templates;
    }

    /**
     * 详情展示
     * @param template 模板信息Domain
     * @return 模板内容
     */
    public String show(Template template){
        StringBuffer stringBuffer = new StringBuffer();
        String fileName = this.getClass().getResource("/").toString();
        fileName = fileName.substring("file:/".length(), fileName.length())+ File.separator + "templet" + File.separator + template.getTemplateName();
        try {
            File file = new File(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String tempString = reader.readLine();
            while (tempString != null) {
                stringBuffer.append(tempString+"\n");
                tempString = reader.readLine();
            }
        } catch (Exception e) {
            throw new RuntimeException("");
        }
        return stringBuffer.toString();
    }
}
